package data

import (
	"errors"
	"strconv"
)

type Basic struct {
	db *DB
}

func NewBasic(
	db *DB,
) (*Basic, error) {
	return &Basic{
		db: db,
	}, nil
}

func (s *Basic) getCfg(key string) (*SystemConfig, error) {
	lists := make([]*SystemConfig, 0)
	s.db.db.Model(&SystemConfig{}).Where("cfg_key = ?", key).Limit(1).Find(&lists)
	if len(lists) == 0 {
		return nil, errors.New("system config is not found")
	}
	return lists[0], nil
}

func (s *Basic) getCfgStr(key string) (string, error) {
	tmp, err := s.getCfg(key)
	if err != nil {
		return "", err
	}
	if tmp.CfgVal == nil {
		return "", nil
	}
	return *tmp.CfgVal, nil
}

func (s *Basic) getCfgInt(key string) (int64, error) {
	tmp, err := s.getCfgStr(key)
	if err != nil {
		return 0, err
	}
	if tmp == "" {
		return 0, errors.New("配置值不合法")
	}
	i64, err := strconv.ParseInt(tmp, 10, 64)
	return i64, err
}

func (s *Basic) getCfgFloat(key string) (float64, error) {
	tmp, err := s.getCfgStr(key)
	if err != nil {
		return 0, err
	}
	if tmp == "" {
		return 0, errors.New("配置值不合法")
	}
	i64, err := strconv.ParseFloat(tmp, 64)
	return i64, err
}
